package com.xhb.sonar.client.builder;

import com.alibaba.fastjson.JSONObject;
import com.xhb.sonar.client.api.IssuesRpcService;
import feign.*;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.form.FormEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Base64;

/**
 * 用来构造Api
 */
public class ApiBuilder {

    private String username;
    private String password;
    private String url;

    public ApiBuilder(String username, String password, String url) {
        this.username = username;
        this.password = password;
        this.url = url;
    }


    public <T> T buildApi(Class<T> clazz) {
        return Feign.builder()
                .decoder(new FastJsonDecoder())
                .encoder(new FormEncoder())
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .requestInterceptor(requestTemplate ->
                        requestTemplate.header("Authorization",
                                "Basic " + getBASE64(username + ":" + password)
                        )
                ).requestInterceptor(requestTemplate ->
                        requestTemplate.header("Content-Type", "URLENCODED")
                ).target(
                        clazz,
                        url
                );
    }

    public <T> T buildApiNoJson(Class<T> clazz) {
        return Feign.builder()
                .encoder(new FormEncoder())
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .requestInterceptor(requestTemplate ->
                        requestTemplate.header("Authorization",
                                "Basic " + getBASE64(username + ":" + password)
                        )
                ).requestInterceptor(requestTemplate ->
                        requestTemplate.header("Content-Type", "URLENCODED")
                ).target(
                        clazz,
                        url
                );
    }

    public static class FastJsonDecoder implements Decoder {

        @Override
        public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(response.body().asReader(Util.UTF_8));
            String line = null;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            System.out.println(content);
            try {
                return JSONObject.parseObject(content.toString(), Class.forName(type.getTypeName()));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    /**
     * 将 s 进行 BASE64 编码
     *
     * @param s
     * @return
     */
    public static String getBASE64(String s) {
        if (s == null) {
            return null;
        }
        return byte2Base64(s.getBytes());
    }

    /**
     * byte数组转base64字符串
     *
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes) {
        try {
            return new String(Base64.getEncoder().encode(bytes), "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
